package com.commander.spring.cloud.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.commander.spring.cloud.common.TX;
import com.commander.spring.cloud.dao.login.LoginDao;
import com.commander.spring.cloud.dao.login.LoginEntity;
import com.commander.spring.cloud.dao.user.UserDao;
import com.commander.spring.cloud.dao.user.UserEntity;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

/**
 * description:
 * <p>
 * Date: 2020-06-05
 * <p>
 * Time: 11:54
 *
 * @author zhangxin
 */
@Service
public class UserServiceImpl implements UserService{
	
	@Autowired
	private LoginDao loginDao;
	@Autowired
	private UserDao userDao;
	
	@TX
	@Override
	public boolean register(UserRegisterRequest request) {
		Assert.notNull(request, "request");
		
		UserEntity user = request.getUser();
		LoginEntity login = request.getLogin();
		
		int result = userDao.saveNew(user);
		if(result == 0){
			throw new RuntimeException("保存用户失败");
		}
		
		result = loginDao.insert(login);
		if(result == 0){
			throw new RuntimeException("保存登录信息失败");
		}
		return true;
	}
	
	@Override
	public boolean updatePhone(String id, String phone) {
		Assert.hasText(id, "id");
		Assert.hasText(phone, "phone");
		
		QueryWrapper<UserEntity> userEntityQueryWrapper = new QueryWrapper();
		userEntityQueryWrapper.eq("id", id);
		UserEntity userEntity = userDao.selectOne(userEntityQueryWrapper);
		userEntity.setPhone(phone);
		UpdateWrapper<UserEntity> updateWrapper = new UpdateWrapper();
		updateWrapper.eq("id", id);
		int result = userDao.update(userEntity, updateWrapper);
		if(result == 0){
			throw new RuntimeException("保存用户失败");
		}
		
		QueryWrapper<LoginEntity> loginEntityQueryWrapper = new QueryWrapper();
		loginEntityQueryWrapper.eq("id", id);
		LoginEntity loginEntity = loginDao.selectOne(loginEntityQueryWrapper);
		loginEntity.setPhone(userEntity.getPhone());
		UpdateWrapper<LoginEntity> loginUpdateWrapper = new UpdateWrapper();
		loginUpdateWrapper.eq("id", id);
		result = loginDao.update(loginEntity, loginUpdateWrapper);
		if(result == 0){
			throw new RuntimeException("保存登录信息失败");
		}
		
		return true;
	}
	
	@Override
	public UserEntity get(String id) {
		Assert.hasText(id, "id");
		
		QueryWrapper<UserEntity> queryWrapper = new QueryWrapper();
		queryWrapper.eq("id", id);
		UserEntity entity = userDao.selectOne(queryWrapper);
		return entity;
	}
	
}
